﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRevitWndr.InsertDoorAndWindow.Cmd;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YJKMenuAssist.Controls;
using YJKMenuAssist.Utility;
using YJKRevitWallModule.WallModule.CreateWall;

namespace YJKMenuAssist
{
	public partial class MainPage : Page, IDockablePaneProvider, IComponentConnector
	{
		private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
		{
			for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
			{
				DependencyObject child = VisualTreeHelper.GetChild(obj, i);
				if (child != null && child is childItem)
				{
					return (childItem)((object)child);
				}
				childItem childItem2 = this.FindVisualChild<childItem>(child);
				if (childItem2 != null)
				{
					return childItem2;
				}
			}
			return default(childItem);
		}

		public MainPage(CommandTableInfos commandTableInfos)
		{
			this.InitializeComponent();
			this.m_CommandTableInfos = commandTableInfos;
			this.leftTab.btnMenuManage.Click += this.MenuManage_Click;
			this.InitializeTabControl(this.m_CommandTableInfos);
			this.m_Handler = new CmdsExternalEventHandler(MainPage.m_CommandData, MainPage.m_Elements);
			this.m_ExternalEvent = ExternalEvent.Create(this.m_Handler);
		}

		public static bool IsInitializedCommandData()
		{
			return MainPage.m_CommandData != null;
		}

		public void SetCommandData(ExternalCommandData commandData)
		{
			MainPage.m_CommandData = commandData;
			if (this.m_Handler != null)
			{
				this.m_Handler.CommandData = commandData;
			}
		}

		public void InitializeTabControl(CommandTableInfos commandTableInfos)
		{
			this.m_CommandTableInfos = commandTableInfos;
			this.leftTab.CmndTableInfos = this.m_CommandTableInfos;
			this.leftTab.Initialize(this, MainPage.m_CommandData);
			this.leftTab.ClickItem += this.mltc_ClickItem;
			this.rightTab.ClickItem += this.mrtc_ClickItem;
			this.RefRightList("轴网", "1");
		}

		private void MenuManage_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				string text = Path.Combine(Product.UserDataLocation, "CustomMenu.xml");
				if (!File.Exists(text))
				{
					File.Copy(Path.Combine(Product.DataLocation, "CustomMenu.xml"), text, true);
				}
				XmlManager xmlManager = new XmlManager(text);
				xmlManager.ImportOpeningByXml(out this.m_CommandTableInfos, "Original");
				if (MainPage.m_CommandData != null)
				{
					MenuManageForm menuManageForm = new MenuManageForm(this.m_CommandTableInfos, MainPage.m_CommandData);
					MainPage.SetFormParentHandle(menuManageForm);
					bool value = menuManageForm.ShowDialog().Value;
					this.leftTab.leftWrapPanel.Children.Clear();
					xmlManager.ImportOpeningByXml(out this.m_CommandTableInfos, "Custom");
					this.InitializeTabControl(this.m_CommandTableInfos);
				}
			}
			catch
			{
			}
		}

		public static void SetFormParentHandle(Window form)
		{
			new WindowInteropHelper(form).Owner = Process.GetCurrentProcess().MainWindowHandle;
		}

		private void mrtc_ClickItem(object sender, RoutedEventArgs e)
		{
			if (MainPage.m_CommandData == null)
			{
				return;
			}
			CommandInfos currentCmdInfos = this.GetCurrentCmdInfos((Label)sender);
			if (currentCmdInfos != null)
			{
				this.m_Handler.CurrentCmdInfos = currentCmdInfos;
				this.m_ExternalEvent.Raise();
			}
		}

		private CommandInfos GetCurrentCmdInfos(Label lable)
		{
			string text = lable.Content.ToString();
			List<string> list = lable.Tag as List<string>;
			if (list.Count > 0)
			{
				return this.SelectCmd(list);
			}
			try
			{
				TableInfos tableInfos = null;
				foreach (TableInfos tableInfos2 in this.m_CommandTableInfos.TableInofList)
				{
					if (this.m_CommandTableInfos.CurrentTabName.CompareTo(tableInfos2.TableName) == 0)
					{
						tableInfos = tableInfos2;
						break;
					}
				}
				foreach (CommandInfos commandInfos in tableInfos.CommandInfoList)
				{
					if (text.CompareTo(commandInfos.CmdName) == 0)
					{
						return commandInfos;
					}
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		private CommandInfos SelectCmd(List<string> lstTag)
		{
			DrawWallCmd.m_strWallFSType = null;
			return this.CheckCmdName(lstTag);
		}

		private void mltc_ClickItem(object sender, RoutedEventArgs e)
		{
			Button button = sender as Button;
			int num = (int)button.Tag;
			this.RefRightList(button.Content.ToString(), num.ToString());
		}

		private void RefRightList(string strName, string strTag)
		{
			try
			{
				this.OnlyShowType(strName);
				TableInfos tableInofList = this.GetTableInofList(strName);
				if (tableInofList != null && strTag != "-1")
				{
					this.rightTab.CmdTableInfos = tableInofList;
					this.rightTab.Initialize();
				}
			}
			catch
			{
			}
		}

		private CommandInfos CheckCmdName(List<string> lstTag)
		{
			CommandInfos result = null;
			string a = lstTag[0];
			if (!(a == "绘制墙体"))
			{
				if (!(a == "插入门"))
				{
					if (a == "插入窗")
					{
						CmdInsertWin.m_strFamilyName = lstTag[2];
						CmdInsertWin.m_strFamilyType = lstTag[1];
						result = this.CreateInfos(lstTag, "YJKRevitWndr.dll", "YJKRevitWndr.InsertDoorAndWindow.Cmd.CmdInsertWin");
					}
				}
				else
				{
					CmdInsertDoor.m_strFamilyName = lstTag[2];
					CmdInsertDoor.m_strFamilyType = lstTag[1];
					result = this.CreateInfos(lstTag, "YJKRevitWndr.dll", "YJKRevitWndr.InsertDoorAndWindow.Cmd.CmdInsertDoor");
				}
			}
			else
			{
				DrawWallCmd.m_strWallFSType = lstTag[1];
				result = this.CreateInfos(lstTag, "YJKRevitWallModule.dll", "YJKRevitWallModule.WallModule.CreateWall.DrawWallCmd");
			}
			return result;
		}

		private CommandInfos CreateInfos(List<string> lstTag, string dllName, string className)
		{
			CommandInfos commandInfos = new CommandInfos();
			commandInfos.CmdName = lstTag[0];
			commandInfos.DllName = dllName;
			commandInfos.ClassName = className;
			this.m_Handler.SetFamilySymbolType(lstTag[2], lstTag[1]);
			return commandInfos;
		}

		private void OnlyShowType(string sName)
		{
			if (sName.CompareTo("墙") == 0)
			{
				ICollection<Element> collection = new FilteredElementCollector(MainPage.m_CommandData.Application.ActiveUIDocument.Document).OfClass(typeof(WallType)).WhereElementIsElementType().ToElements();
				this.rightTab.Initialize_GeneraType(collection, "墙");
				this.m_CommandTableInfos.CurrentTabName = sName;
				return;
			}
			if (sName.CompareTo("门") == 0)
			{
				ICollection<Element> collection2 = new FilteredElementCollector(MainPage.m_CommandData.Application.ActiveUIDocument.Document).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Doors).WhereElementIsElementType().ToElements();
				this.rightTab.Initialize_GeneraType(collection2, "门");
				this.m_CommandTableInfos.CurrentTabName = sName;
				return;
			}
			if (sName.CompareTo("窗") == 0)
			{
				ICollection<Element> collection3 = new FilteredElementCollector(MainPage.m_CommandData.Application.ActiveUIDocument.Document).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Windows).WhereElementIsElementType().ToElements();
				this.rightTab.Initialize_GeneraType(collection3, "窗");
				this.m_CommandTableInfos.CurrentTabName = sName;
				return;
			}
		}

		private void GetXYDpiScale(ref double xDPICalel, ref double yDPICalel)
		{
			if (MainPage.m_CommandData != null)
			{
				string versionNumber = MainPage.m_CommandData.Application.Application.VersionNumber;
				int num = -1;
				if (!this.StringToInt32(versionNumber, ref num))
				{
					return;
				}
				if (num > 2017)
				{
					return;
				}
				WinDPIManager.GetWpfXYDpiScale(this, ref xDPICalel, ref yDPICalel);
			}
		}

		private bool StringToInt32(string strValue, ref int nValue)
		{
			bool result;
			try
			{
				nValue = Convert.ToInt32(strValue);
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private double GetXDPIScale()
		{
			this.GetXYDpiScale(ref this.m_XDPIScale, ref this.m_YDPIScale);
			if (Common.Lessthan_Or_Equal(this.m_XDPIScale, 0.0) || Common.GreaterThan(this.m_XDPIScale, 10.0))
			{
				this.m_XDPIScale = 1.0;
			}
			return this.m_XDPIScale;
		}

		private double GetYDPIScale()
		{
			this.GetXYDpiScale(ref this.m_XDPIScale, ref this.m_YDPIScale);
			if (Common.Lessthan_Or_Equal(this.m_YDPIScale, 0.0) || Common.GreaterThan(this.m_YDPIScale, 10.0))
			{
				this.m_YDPIScale = 1.0;
			}
			return this.m_YDPIScale;
		}

		public void SetupDockablePane(DockablePaneProviderData data)
		{
			data.FrameworkElement = this;
			new DockablePaneProviderData();
			data.InitialState = new DockablePaneState();
			data.InitialState.DockPosition = this.m_position;
			DockablePaneId tabBehind;
			if (this.m_targetGuid == Guid.Empty)
			{
				tabBehind = null;
			}
			else
			{
				tabBehind = new DockablePaneId(this.m_targetGuid);
			}
            if ((int)this.m_position == 59424)
			{
				data.InitialState.TabBehind = tabBehind;
			}
            if ((int)this.m_position == 59423)
			{
				RevitVersionFuncs.SetFloatingRectangle(ref data, this.m_left, this.m_top, this.m_right, this.m_bottom);
			}
		}

		public void SetInitialDockingParameters(int left, int right, int top, int bottom, DockPosition position, Guid targetGuid)
		{
			this.m_position = position;
			this.m_left = left;
			this.m_right = right;
			this.m_top = top;
			this.m_bottom = bottom;
			this.m_targetGuid = targetGuid;
		}

		private TableInfos GetTableInofList(string strTableName)
		{
			try
			{
				foreach (TableInfos tableInfos in this.m_CommandTableInfos.TableInofList)
				{
					if (strTableName.CompareTo(tableInfos.TableName) == 0)
					{
						this.m_CommandTableInfos.CurrentTabName = strTableName;
						return tableInfos;
					}
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		private static void ChangeFocus()
		{
			try
			{
				UIApplication application = MainPage.m_CommandData.Application;
				Autodesk.Revit.DB.View activeView = application.ActiveUIDocument.ActiveView;
				foreach (UIView uiview in application.ActiveUIDocument.GetOpenUIViews())
				{
					if (activeView == null || uiview.ViewId.IntegerValue != activeView.Id.IntegerValue)
					{
						Autodesk.Revit.DB.View activeView2 = MainPage.m_CommandData.Application.ActiveUIDocument.Document.GetElement(uiview.ViewId) as Autodesk.Revit.DB.View;
						application.ActiveUIDocument.ActiveView = activeView2;
						application.ActiveUIDocument.ActiveView = activeView;
						return;
					}
				}
				FilteredElementIterator elementIterator = new FilteredElementCollector(application.ActiveUIDocument.Document).OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator();
				elementIterator.Reset();
				while (elementIterator.MoveNext())
				{
					Element element = elementIterator.Current;
					Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View;
					if (view != null && !view.IsTemplate && view.Id.IntegerValue != activeView.Id.IntegerValue && ((int)view.ViewType == 4 || (int)view.ViewType == 1 || (int)view.ViewType == 2 || (int)view.ViewType == 3 || (int)view.ViewType == 117))
					{
						application.ActiveUIDocument.ActiveView = view;
						application.ActiveUIDocument.ActiveView = activeView;
						break;
					}
				}
			}
			catch (Exception ex)
			{
				string message = ex.Message;
			}
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
		}

		private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
		{
		}

        //[DebuggerNonUserCode]
        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //public void InitializeComponent()
        //{
        //    if (this._contentLoaded)
        //    {
        //        return;
        //    }
        //    this._contentLoaded = true;
        //    Uri resourceLocator = new Uri("/YJKMenuAssist;component/mainpage/mainpage.xaml", UriKind.Relative);
        //    Application.LoadComponent(this, resourceLocator);
        //}

        //[DebuggerNonUserCode]
        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //internal Delegate _CreateDelegate(Type delegateType, string handler)
        //{
        //    return Delegate.CreateDelegate(delegateType, this, handler);
        //}

        //[DebuggerNonUserCode]
        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //[EditorBrowsable(EditorBrowsableState.Never)]
        //void IComponentConnector.Connect(int connectionId, object target)
        //{
        //    switch (connectionId)
        //    {
        //    case 1:
        //        this.MainPanel = (MainPage)target;
        //        this.MainPanel.Loaded += this.Page_Loaded;
        //        this.MainPanel.SizeChanged += this.Page_SizeChanged;
        //        return;
        //    case 2:
        //        this.rightTab = (RightTabControl)target;
        //        return;
        //    case 3:
        //        this.leftTab = (LeftTabControl)target;
        //        return;
        //    default:
        //        this._contentLoaded = true;
        //        return;
        //    }
        //}

		public static ExternalCommandData m_CommandData = null;

		private static ElementSet m_Elements = new ElementSet();

		private ExternalEvent m_ExternalEvent;

		private CmdsExternalEventHandler m_Handler;

		private Guid m_targetGuid;

        private DockPosition m_position = (DockPosition)59422;

		private int m_left = 1;

		private int m_right = 1;

		private int m_top = 1;

		private int m_bottom = 1;

		private double m_XDPIScale;

		private double m_YDPIScale;

		private CommandTableInfos m_CommandTableInfos;

        //internal MainPage MainPanel;

		internal RightTabControl rightTab;

		internal LeftTabControl leftTab;

        //private bool _contentLoaded;
	}
}
